<?php
	namespace Admin\Controller;
	use 	Think\Controller;
	header('content-type:text/html;charset=utf-8');
	class BookController extends PublicController{
		//图书列表页
		public function index()
		{
			//实例化model类
			$book = M('book');

			//计算书籍总条数
			$count = $book->where('status=1')->count();

			//实例化分页类
			$page = new \Think\Page($count,5);

			//查询出所有数据库信息
			$data = $book->limit($page->firstRow.','.$page->listRows)->select();

			//实现分页分能
			$page->setConfig('header','个会员');
	    	$page->setConfig('first','首页');
	    	$page->setConfig('last','末页');
	    	$page->setConfig('prev','上一页');
	    	$page->setConfig('next','下一页');
	    	$page->setConfig('theme',"共 %TOTAL_ROW% 条记录 %FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%");

			//分页显示输出
			$show = $page->show();

			//赋值变量
			$this->assign('data',$data);
			$this->assign('show',$show);

			//输出模版
			$this->display();
		}

		//添加图书页
		public function add()
		{
			//实例化model类
			$type = M('book_types');

			//查询出所有分类信息
			$data = $type->select();

			//实例化分类类
			$result =  \Org\LAMP\CatTree::getlist($data);
			//dump($result);exit;
			
			//赋值变量
			$this->assign('data',$result);

			$this->display();
		}

		//执行添加功能
		public function insert()
		{
			//实例化model类
			$book = M('book');
			$book_pic = M('book_pic');
			//dump($_FILES['bkpic']);exit;
			//开启事物
			$book->startTrans();
			//上传文件配置
			$config = array(
				'rootPath' =>'Public/',
				'savePath' =>'Uploads/',
				'exts'     =>array('gif','png','jpg','jpeg'),
				'saveName' =>date('YmdHis')
				);
			//实例化文件上传类
			$upload = new \Think\Upload($config);

			//将文件上传到服务器
			$res = $upload->upload();
			$i = 1;
			foreach($res as $key => $value){
				if($i==1){
					$_POST['bkpic'] = $value['savepath'].$value['savename'];
				}
				
			}


			// 2.创建一个安全的数据信息(I函数的功能包含进来)
			//$res1 = $book->create($_POST);
			//dump(I('post.'));
			//执行插入数据库

			$res1 = $book->add(I('post.'));
			//echo $book->_sql();

			//dump($res1);exit;

			//添加所有图片到数据库
			if($res1){
				$data['bid'] = $res1;
				foreach($res as $key=>$value){
					$data['bookpic'] = $value['savepath'].$value['savename']; 

					//执行插入语句
					$res2 = $book_pic->add($data);
					if($res2){
						//提交事物
						$book->commit();
						$this->success('添加成功',U('book/index'),2);
					}else{
						//插入失败 回滚事物
						$book->rollback();
						$this->error('添加失败');
					}
				}

			}else{
				$this->error('添加图书失败');
			}
		}

		//根据id查询数据
		public function edit()
		{
			//实例化model类
			$book = M();
			//两表联查
			$id = I('get.id');

			//执行两表联查
			$data = $book->field('b.id,b.bkname,b.bkprice,b.bkpic,b.bknum,b.bkdes,t.typename,p.bookpic')->table('__BOOK__ b,__BOOK_PIC__ p,__BOOK_TYPES__ t')->where("b.id={$id} and b.id=p.bid and b.status=1 and b.tid=t.id")->find();
			// echo $book->_sql();
			// dump($data);exit;
			
			//赋值变量
			$this->assign('data',$data);

			//输出模版
			$this->display();


		}



	}
